package fr.uha.ensisa.kfetmanager.category.admin;

import fr.uha.ensisa.kfetmanager.category.CustomerCategory;
import fr.uha.ensisa.kfetmanager.category.CustomerCategoryManagerRemote;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author JC
 */
public class AdminCategoriesEdit extends HttpServlet {

    @EJB
    private CustomerCategoryManagerRemote categoryManager;
    private final String errorPage = "/error.jsp";
    private final String home = "/admin/categories";
    private final String edit = "/admin/categories/edit";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idString = request.getParameter("id");
        Long id;
        // Parse ID parameter
        try {
            id = Long.parseLong(idString);
        } catch (Exception e) {
            this.getServletContext().setAttribute("errorMessage", "ID non valide");
            this.getServletContext().setAttribute("redirectTo", home);
            this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
            return;
        }

        // Get CustomerCategory object by ID and handle errors
        CustomerCategory c = categoryManager.getCategory(id);
        if (c == null) {
            this.getServletContext().setAttribute("errorMessage", "Aucune cat&eacute;gorie avec cette ID");
            this.getServletContext().setAttribute("redirectTo", home);
            this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
            return;
        }

        // If the method is GET, forward request to AdminCategories.jsp to display the form.
        // If the method is POST, get all the parameters and perform actual edit

        if (request.getMethod().equals("GET")) {
            this.getServletContext().setAttribute("action", "edit");
            this.getServletContext().setAttribute("category", c);
            this.getServletContext().getRequestDispatcher("/admin/AdminCategories.jsp").forward(request, response);

        } else {
            String label = request.getParameter("label");

            // Check if label has been specified
            if (label == null) {
                this.getServletContext().setAttribute("errorMessage", "Label n'a pas &eacute;t&eacute; sp&eacute;cifi&eacute;");
                this.getServletContext().setAttribute("redirectTo", edit + "?id=" + idString);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Check if label is empty string
            if (label.isEmpty()) {
                this.getServletContext().setAttribute("errorMessage", "Label est vide");
                this.getServletContext().setAttribute("redirectTo", edit + "?id=" + idString);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Check if label already exists (only if different from current)
            if (!label.equals(c.getLabel()) && categoryManager.exists(label)) {
                this.getServletContext().setAttribute("errorMessage", "Ce label existe d&eacute;j&agrave;");
                this.getServletContext().setAttribute("redirectTo", edit + "?id=" + idString);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Edit category
            try {
                categoryManager.updateCategory(c, label);
            } catch (Exception e) {
                this.getServletContext().setAttribute("errorMessage", "Erreur lors de la modification de cat&eacute;gorie");
                this.getServletContext().setAttribute("redirectTo", edit + "?id=" + idString);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Redirect to home page
            response.sendRedirect(getServletContext().getContextPath() + home);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
